//
//  SearchViewController.m
//  bestkeep
//
//  Created by yons on 16/11/18.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "SearchViewController.h"
#import "BKSearch_CustomTextField.h"
#import "RequestManager+BK.h"
#import "BKSearchCommon.h"
#import "Mediator+BKClassify.h"
#import "BKMainCommon.h"

#define LeftInterSpace    16.5  //左边间隙
#define Tag_HotBase       10000 //热门搜索按钮基准值
#define Tag_RecentBase    20000 //最近搜索按钮基准值
#define MaxLen            10000 //输入框允许的最大长度
#define MaxCount_RecentSearch   12 //最近搜索最多显示条数


@interface SearchViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)NSArray *hotArray;//搜索热门数据--数组
@property(nonatomic,strong)NSMutableArray *searchBtnArray;//存放所有按钮
@property(nonatomic,strong)NSMutableArray *recentSearchArr;//最近搜索数据
@property(nonatomic,strong)NSString *filePath;
@property(nonatomic,assign)float float_hotHeight;//热门高度
@property(nonatomic,assign)float float_recentHeight;//最近高度
@property(nonatomic,strong)UIView *containerView;
@property(nonatomic, strong)UIView *view_hotSearch;    //热门视图
@property(nonatomic, strong)UIView *view_recentSearch;   //最近搜索视图
@property(nonatomic,strong)UIView *searchBarView;
@property(nonatomic,strong)UIButton *cancelBtn;
@property(nonatomic,strong)UIImageView *messageImageView;
@property(nonatomic,strong)UILabel *cancelLabel;
@property(nonatomic,strong)UIButton *deleteBtn;
@property(nonatomic,strong)UIButton *searchBtn;
@property(nonatomic,strong)BKSearch_CustomTextField *textField;
@property(nonatomic,strong)ExceptionView *exceptionView;
@property (nonatomic, strong) UIView *separateView;


@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializeComponent];
    [self setUpSearchBar];
    
    
}

-(void)createSeparateView{

    _separateView = [UIView new];
    _separateView.backgroundColor = [UIColor whiteColor];
    [self.containerView addSubview:_separateView];
    [_separateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.containerView.mas_top).offset(_float_hotHeight + 10);
        make.left.equalTo(self.containerView.mas_left);
        make.right.equalTo(self.containerView.mas_right);
        make.height.equalTo(@10);
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden = NO;
    [self requestData];
    
    if (iPhone6P) {
        _searchBarView.frame = CGRectMake(50, 0, ScreenWidth-53-8-50-4, 30);
        
    }else{
        _searchBarView.frame = CGRectMake(50, 0, ScreenWidth-53-8-50, 30);
        
    }
    [UIView animateWithDuration:0.1 animations:^{
        _cancelLabel.hidden = YES;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            _messageImageView.frame = CGRectMake(_messageImageView.center.x, _messageImageView.center.y, 0, 0);
            if (iPhone6P) {
                _searchBarView.frame = CGRectMake(0, 0, ScreenWidth-53-8-4, 30);
                
            }else{
                _searchBarView.frame = CGRectMake(0, 0, ScreenWidth-53-8, 30);
            }
        } completion:^(BOOL finished) {
            _messageImageView.image = nil;
            _cancelLabel.hidden = NO;
            _messageImageView.frame = CGRectMake(ScreenWidth-38-8, 3, 23, 23);
            if (iPhone6P) {
                _searchBarView.frame = CGRectMake(0, 0, ScreenWidth-53-8-4, 30);
            }else{
                _searchBarView.frame = CGRectMake(0, 0, ScreenWidth-53-8, 30);
            }
        }];
        
        
    }];
    
    
    
}

-(void)viewWillDisappear:(BOOL)animated{
    
}

-(void)initializeComponent{
    self.view.backgroundColor = [UIColor whiteColor];// [UIColor colorWithWhite:0.902 alpha:1.000];
    self.navigationItem.leftBarButtonItem = nil;
    _hotArray = [[NSArray alloc]init];
    _searchBtnArray = [[NSMutableArray alloc]init];
    _float_hotHeight = 40;
    _float_recentHeight = 100;
    _scrollView = [UIScrollView new];
    _scrollView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_scrollView];
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0,0,0,0));
    }];
    _containerView = [UIView new];
    [_scrollView addSubview:_containerView];
    [_containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_scrollView);
        make.width.equalTo(_scrollView);
    }];
    
    UITapGestureRecognizer *cancelTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelTap)];
    [self.view addGestureRecognizer:cancelTap];
    
    
}
-(void)cancelTap{
    [self.view endEditing:YES];
}
#pragma mark -------------设置搜索导航bar-----------------------
-(void)setUpSearchBar{
    UIView *bigView = [[UIView alloc]init];
    bigView.backgroundColor = [UIColor clearColor];
    bigView.layer.masksToBounds = YES;
    bigView.layer.cornerRadius = 15;
    
    _searchBarView = [[UIView alloc]initWithFrame:CGRectMake(4, 0, ScreenWidth-53-8, 30)];
    _searchBarView.backgroundColor = RGBACOLOR(218, 218, 218, 0.5);
    _searchBarView.layer.masksToBounds = YES;
    _searchBarView.layer.cornerRadius = 15;
    [bigView addSubview:_searchBarView];
    
    _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancelBtn.frame = CGRectMake(ScreenWidth-53-8, 0, 53, 30);
    [_cancelBtn setTitleColor:RGBACOLOR(136, 136, 136, 1) forState:UIControlStateNormal];
    [_cancelBtn addTarget:self action:@selector(cancelBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [bigView addSubview:_cancelBtn];
    
    _messageImageView = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth-38-8, 3, 23, 23)];
    _messageImageView.image = [UIImage imageNamed:@"BKMain_消息中心icon"];
    [bigView addSubview:_messageImageView];
    
    _cancelLabel = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-53-8, 0, 53, 30)];
    _cancelLabel.text = @"取消";
    _cancelLabel.font = [Common systemFontOfSize:14];
    _cancelLabel.textColor = RGBACOLOR(136, 136, 136, 1.0);
    _cancelLabel.textAlignment = NSTextAlignmentCenter;
    [bigView addSubview:_cancelLabel];
    
    _searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _searchBtn.frame = CGRectMake(7.5, 3.5, 23, 23);
    _searchBtn.titleLabel.font = [Common systemFontOfSize:18];
    [_searchBtn setImage:[UIImage imageNamed:@"searchIcon"] forState:UIControlStateNormal];
    [_searchBarView addSubview:_searchBtn];
    
    _textField = [[BKSearch_CustomTextField alloc]init];
    [_textField setFrame:CGRectMake(30, 0, ScreenWidth-110, 30)];
    _textField.delegate = self;
    _textField.font = [Common systemFontOfSize:14];
    _textField.backgroundColor = [UIColor clearColor];
    _textField.textColor = RGBACOLOR(178, 178, 178, 1.0);
    _textField.placeholder = @"请输入商品名称";
    
    [_textField addTarget:self action:@selector(textFiledAction) forControlEvents:UIControlEventEditingChanged];
    _textField.returnKeyType = UIReturnKeySearch;
    [_searchBarView addSubview:_textField];
    _deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_deleteBtn setImage:[UIImage imageNamed:@"BKSearch_quancha"] forState:UIControlStateNormal];
    _deleteBtn.hidden = YES;
    [_deleteBtn addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
    [_searchBarView addSubview:_deleteBtn];
    [_deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(_searchBarView.mas_right).offset(3);
        make.top.mas_equalTo(_searchBarView.mas_top).offset(0);
        make.height.mas_equalTo(@(30));
        make.width.mas_equalTo(@(30));
    }];
    
    
    if (iPhone6P) {
        _cancelLabel.frame = CGRectMake(ScreenWidth-53-8-4, 0, 53, 30);
        _cancelBtn.frame = CGRectMake(ScreenWidth-53-8-4, 0, 53, 30);
        _searchBarView.frame = CGRectMake(0, 0, ScreenWidth-53-8-4, 30);
        
    }else{
        _searchBarView.frame = CGRectMake(0, 0, ScreenWidth-53-8, 30);
    }
    
    self.navigationItem.titleView = bigView;
    self.navigationItem.titleView.frame = CGRectMake(0, 0, ScreenWidth, 30);
}
-(void)deleteAction{
    _textField.text = nil;
    _deleteBtn.hidden = YES;
}
//取消按钮回调
-(void)cancelBtnAction{
    [self.navigationController popViewControllerAnimated:NO];
    
}

- (void)textFiledAction{
    if (!_textField.text.length) {
        _deleteBtn.hidden = YES;
    }else{
        _deleteBtn.hidden = NO;
    }
}

#pragma mark ---------------UITextFiledDelegate---------
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    if ([_textField.text isEqualToString:@""]) {
        [HUD showMessage:@"请输入关键字"];
        
    }else{
        NSMutableArray *dataArr = [NSMutableArray arrayWithContentsOfFile:self.filePath];
        NSMutableArray *itemArr = [NSMutableArray arrayWithArray:dataArr];
        for (NSString *string in itemArr) {
            if ([string isEqualToString:textField.text]) {
                [dataArr removeObjectAtIndex:[itemArr indexOfObject:string]];
            }else{
                
            }
        }
        [dataArr addObject:textField.text];
        [dataArr writeToFile:self.filePath atomically:YES];
        
        
#pragma mark --- 此处跳转---
        
        UIViewController *searchResultVC = [[Mediator sharedInstance] classifyWithFilterTerms:@"-1" categotyId:@"" channelType:@"" orderKey:@"" currentPage:0 keyWord:_textField.text order:@"" classifyType:@"1"];
        [self.navigationController pushViewController:searchResultVC animated:YES];
        
    }
    return YES;
}

//最近搜索关键字写入本地
-(void)cacheSearchKey{
    _recentSearchArr = [[NSMutableArray alloc]init];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"searchKey.plist"];
    self.filePath = filePath;
    NSMutableArray *dataArr = [NSMutableArray arrayWithContentsOfFile:filePath];
    NSLog(@"%@",dataArr);
    if (dataArr == nil) {
        NSMutableArray *arr = [[NSMutableArray alloc]init];
        [arr writeToFile:filePath atomically:YES];
    }
    _recentSearchArr = [NSMutableArray arrayWithContentsOfFile:filePath];
    
}
#pragma UI-热门搜索
-(void)createHotBtn{
    /**
     * 热门视图
     */
    UIView * view_hotSearch = [[UIView alloc]init];
    [_containerView addSubview:view_hotSearch];
    _view_hotSearch = view_hotSearch;
    _view_hotSearch.backgroundColor = [UIColor clearColor];
    [_view_hotSearch mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_containerView.mas_right).offset(0);
        make.top.equalTo(_containerView.mas_top).offset(0);
        make.height.mas_equalTo(@(ScreenWidth));
        make.width.mas_equalTo(@(ScreenWidth));
    }];
    
    /**
     *  热搜图标
     */
    UIImageView *hotbtn = [UIImageView new];
    hotbtn.frame = CGRectMake(15, 10, 23, 23);
    //    [hotbtn setBackgroundImage:[UIImage imageNamed:@"hot_search"] forState:UIControlStateNormal];
    hotbtn.contentMode = UIViewContentModeCenter;
    hotbtn.image = [[UIImage imageNamed:@"hot_search"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    hotbtn.tintColor = RGB(153, 153, 153);
    
    
    
    
    
    [_view_hotSearch addSubview:hotbtn];
    
    /**
     * lab 热门搜索
     */
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(50, 10-4, 150, 30)];
    
    label.text = @"热门搜索";
    label.textColor = RGBACOLOR(153, 153, 153, 1.0);
    label.font = [Common systemFontOfSize:14];
    [_view_hotSearch addSubview:label];
}


#pragma mark--------------创建热门搜索按钮组---------------
-(void)HotBtn_WithArr:(NSArray *)array view:(UIView *)view{
    CGFloat cruuentY = 40;
    CGFloat cruuentX = LeftInterSpace;
    CGFloat forwardHeight = 0;
    for (int i = 0; i<array.count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor clearColor];
        button.layer.masksToBounds = YES;
        button.layer.borderColor = RGB(178, 178, 178).CGColor; // [UIColor lightGrayColor].CGColor;
        button.layer.cornerRadius = 2; // 4;
        button.layer.borderWidth = 0.5; //1;
        button.tag = i+Tag_HotBase;
        [button addTarget:self action:@selector(action_HotBtn:) forControlEvents:UIControlEventTouchUpInside];
        NSDictionary *dic = array[i];
        CGSize btnSize = [self boundingRectWithSize:dic[@"categoryName"]  Font:[Common systemFontOfSize:12] Size:CGSizeMake(ScreenWidth - 40, 40)];
        button.titleLabel.font = [Common systemFontOfSize:12];
        button.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
//        [button setTitleColor:[UIColor colorWithWhite:0.200 alpha:1.000] forState:UIControlStateNormal];
        [button setTitleColor:RGB(178, 178, 178) forState:UIControlStateNormal];
        [button setTitle:dic[@"categoryName"] forState:UIControlStateNormal];
        
        if (cruuentX + btnSize.width >ScreenWidth - 10) {
            cruuentX = LeftInterSpace;
            cruuentY = cruuentY + forwardHeight + 10;
        }
        button.frame = CGRectMake(cruuentX, cruuentY, btnSize.width, 25);
        [view addSubview:button];
        forwardHeight = 25;
        cruuentX = cruuentX + btnSize.width + 15; // cruuentX + btnSize.width + 10;
        [_searchBtnArray addObject:button];
    }
    _float_hotHeight = cruuentY+ forwardHeight ;
}

- (CGSize) boundingRectWithSize:(NSString*)string Font:(UIFont*) font Size:(CGSize) size{
    CGSize _size;
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
    NSDictionary *attribute = @{NSFontAttributeName: font};
    NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
    NSStringDrawingUsesLineFragmentOrigin |
    NSStringDrawingUsesFontLeading;
    _size = [string boundingRectWithSize:size options: options attributes:attribute context:nil].size;
#else
    _size = [string sizeWithFont:font constrainedToSize:size];
#endif
    _size.height += 10;
    _size.width += 10;
    return _size;
}
#pragma mark --------热门搜索点击跳转----------------

-(void)action_HotBtn:(UIButton *)button{
    [_textField resignFirstResponder];
    _textField.text = nil;
    button.backgroundColor = RGBACOLOR(3, 191, 160, 1);//设置选中颜色
    for (UIButton *btn in _searchBtnArray) {
        if (btn.tag != button.tag) {
            btn.backgroundColor = [UIColor clearColor];
        }
    }
    //点击热门加入历史记录做本地缓存--已修改如下
//    NSMutableArray *dataArr = [NSMutableArray arrayWithContentsOfFile:self.filePath];
//    NSMutableArray *itemArr = [NSMutableArray arrayWithArray:dataArr];
//    for (NSString *string in itemArr) {
//        if ([string isEqualToString:button.titleLabel.text]) {
//            [dataArr removeObjectAtIndex:[itemArr indexOfObject:string]];
//        }else{
//            
//        }
//    }
//    [dataArr addObject:button.titleLabel.text];
//    [dataArr writeToFile:self.filePath atomically:YES];
    
    
//    UIViewController *searchResultVC = [[Mediator sharedInstance] classifyWithFilterTerms:@"-1" categotyId:@"" channelType:@"" orderKey:@"" currentPage:0 keyWord:_hotArray[button.tag -Tag_HotBase] order:@"" classifyType:@"1"];
    
    NSDictionary *dic = _hotArray[button.tag - Tag_HotBase];
    
    UIViewController *searchResultVC = [[Mediator sharedInstance] classifyWithFilterTerms:@"-1" categotyId:dic[@"categoryId"] channelType:@"" orderKey:@"" currentPage:0 keyWord:@"" order:@"" classifyType:@"1"];
    
    [self.navigationController pushViewController:searchResultVC animated:YES];
}

#pragma mark ----------------- 最近搜索 ----------------

-(void)creatRecentSearchBtn{
    for (NSString *string in _recentSearchArr) {
        if ([string isEqualToString:@""]) {
            [_recentSearchArr removeObject:string];
        }
    }
    _view_recentSearch = [[UIView alloc]init];
    _view_recentSearch.backgroundColor = [UIColor clearColor];
    [_containerView addSubview:_view_recentSearch];
    [_view_recentSearch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_containerView.mas_right);
        make.top.equalTo(_containerView.mas_top).offset(_float_hotHeight + 20);
        make.height.mas_equalTo(@(ScreenWidth-_float_hotHeight));
        make.width.mas_equalTo(@(ScreenWidth));
    }];
    NSLog(@"最近搜索----------%@",self.recentSearchArr);
    
    if (_recentSearchArr.count !=0) {
        NSInteger count_recentSearch;
        if (_recentSearchArr.count > MaxCount_RecentSearch) {
            count_recentSearch = MaxCount_RecentSearch;
        }else{
            count_recentSearch = _recentSearchArr.count;
        }
        
        //搜索图标
        //        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15, 10, 23, 23)];
        //        imageView.image = [UIImage imageNamed:@"search"];
        //        [_view_recentSearch addSubview:imageView];
        //
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:[UIImage imageNamed:@"BKSearch_rerecent_search"] forState:UIControlStateNormal];
        btn.frame = CGRectMake(15, 10, 23, 23);
        [_view_recentSearch addSubview:btn];
        //最近搜索字样
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(50, 10-4, 150, 30)];
        label.text = @"最近搜索";
        label.textColor = RGBACOLOR(153, 153, 153, 1.0);
        label.font = [Common systemFontOfSize:14];
        [_view_recentSearch addSubview:label];
        //删除最近搜索
        UIButton * clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        [clearBtn setBackgroundImage:[UIImage imageNamed:@"BKSearch_delete"] forState:UIControlStateNormal];
        [clearBtn setImage:[UIImage imageNamed:@"BKSearch_delete"] forState:UIControlStateNormal];
        [clearBtn addTarget:self action:@selector(clearBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_view_recentSearch addSubview:clearBtn];
        [clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(_view_recentSearch.mas_right).offset(-15);
            make.top.mas_equalTo(_view_recentSearch.mas_top).offset(6);
            make.height.mas_equalTo(@(32));
            make.width.mas_equalTo(@(30));
        }];
        
        
        [self Recent_Button:count_recentSearch view:_view_recentSearch array:_recentSearchArr];
        
        
        
        
    }
}
//清除按钮回调
- (void)clearBtnAction{
    _separateView.hidden = YES;
    NSMutableArray *itemArr = [NSMutableArray arrayWithContentsOfFile:self.filePath];
    [itemArr removeAllObjects];
    [itemArr writeToFile:self.filePath atomically:YES];
    _view_recentSearch.hidden = YES;
    
}
#pragma mark   -------根据数据布局最近搜索按钮页面---------------
-(void)Recent_Button:(NSInteger )count view:(UIView *)view array:(NSArray *)array{
    CGFloat cruuentY = 40;
    CGFloat cruuentX = LeftInterSpace;
    CGFloat forwardHeight = 0;
    for (int i = 0; i<count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor clearColor];
        button.layer.borderColor = RGB(178, 178, 178).CGColor;//[UIColor lightGrayColor].CGColor;
        button.layer.cornerRadius = 1.5;//4;
        button.layer.borderWidth = 0.5;//1;
        button.tag = i+Tag_RecentBase;
        [button addTarget:self action:@selector(action_RecentBtn:) forControlEvents:UIControlEventTouchUpInside];
        CGSize btnSize = [self boundingRectWithSize:array[count -1 - i]  Font:[Common systemFontOfSize:12] Size:CGSizeMake(ScreenWidth - 40, 40)];
        button.titleLabel.font = [Common systemFontOfSize:12];
        button.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
//        [button setTitleColor:[UIColor colorWithWhite:0.200 alpha:1.000] forState:UIControlStateNormal];
        [button setTitleColor:RGB(178, 178, 178) forState:UIControlStateNormal];
        [button setTitle:array[count -1 - i] forState:UIControlStateNormal];
        if (cruuentX + btnSize.width >ScreenWidth - 10) {
            cruuentX = LeftInterSpace;
            cruuentY = cruuentY + forwardHeight + 10;
        }
        button.frame = CGRectMake(cruuentX, cruuentY, btnSize.width, 25);
        [view addSubview:button];
        forwardHeight = 25;
        cruuentX = cruuentX + btnSize.width + 15;// cruuentX + btnSize.width + 10;
        [_searchBtnArray addObject:button];
    }
    _float_recentHeight = cruuentY+ forwardHeight + 80;
    UIButton *clearBut = [UIButton buttonWithType:UIButtonTypeCustom];
    clearBut.frame = CGRectMake(15, _float_recentHeight-40, ScreenWidth-30, 45);
    clearBut.layer.borderColor = [UIColor lightGrayColor].CGColor;
    clearBut.layer.borderWidth = 1;
    clearBut.layer.cornerRadius = 3;
    clearBut.backgroundColor = [UIColor clearColor];
    [clearBut setTitle:@"清空历史搜索" forState:UIControlStateNormal];
    [clearBut addTarget:self action:@selector(clearBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [clearBut setTitleColor:[UIColor colorWithWhite:0.200 alpha:1.000] forState:UIControlStateNormal];
}
#pragma mark-【最近搜索btn】点击
-(void)action_RecentBtn:(UIButton *)button{
    [_textField resignFirstResponder];
    button.backgroundColor = RGBACOLOR(3, 191, 160, 1);
    for (UIButton *btn in _searchBtnArray) {
        if (btn.tag != button.tag) {
            btn.backgroundColor = [UIColor clearColor];
        }
    }
    NSInteger number;
    if (_recentSearchArr.count > MaxCount_RecentSearch) {
        number = MaxCount_RecentSearch;
    }else{
        number = _recentSearchArr.count;
    }
    NSString  *searchKey = _recentSearchArr[number-1-button.tag+Tag_RecentBase];
    
//    NSMutableArray *temp = [NSMutableArray array];
//    for (NSDictionary *dic in self.hotArray) {
//        [temp addObject:dic[@"categoryName"]];
//    }
//    
//    NSString *categotyId = @"";
//    if ([temp containsObject:searchKey]) {
//        for (NSDictionary *dic in self.hotArray) {
//            if ([searchKey isEqualToString:dic[@"categoryName"]]) {
//                categotyId = dic[@"categoryId"];
//            }
//        }
//        searchKey = @"";
//    }
    
    UIViewController *searchResultVC = [[Mediator sharedInstance] classifyWithFilterTerms:@"-1" categotyId:@"" channelType:@"" orderKey:@"" currentPage:0 keyWord:searchKey order:@"" classifyType:@"1"];
    [self.navigationController pushViewController:searchResultVC animated:YES];
    
    
}
#pragma mark -- --------请求热门数据--------------

- (void)requestData{
    __weak typeof(self) weakSelf = self;
    
//    if (weakSelf.exceptionView) {
//        [weakSelf.exceptionView dismiss];
//        weakSelf.exceptionView = nil;
//    }
    
//    if ([BKMainCommon checkNetWork] == NO) {
//        [self.view endEditing:YES];
//        if (!weakSelf.exceptionView) {
//            weakSelf.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
//            ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
//                [self requestData];
//            }];
//            weakSelf.exceptionView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
//            [weakSelf.exceptionView addAction:retryAction];
//            [weakSelf.exceptionView showInView:self.view];
//        }
//    }else{
//        NSString *url = [BKMainCommon ServicesURL:@"getHotSearchKeyWord"];
    [LoadingView loadingShoppingCartInView:self.view];
    NSString *url = [BKMainCommon ServicesURL:@"getHotSearchCagegory"];
        RequestManager *manger = [RequestManager manager];
        [manger bkDataRequest:RequestMethodGet URLString:url parameters:nil success:^(id  _Nullable responseObject) {
            if(!weakSelf) {
                return;
            }
            __strong typeof(weakSelf) strongSelf = weakSelf;
            
            if(strongSelf.exceptionView) {
                [strongSelf.exceptionView dismiss];
                strongSelf.exceptionView = nil;
            }
            
            if ([responseObject objectForKey:@"success"]) {
                [self cacheSearchKey];
                [self createHotBtn];
                [self createSeparateView];
                [self creatRecentSearchBtn];
                [self.textField becomeFirstResponder];
                
                self.view_hotSearch.hidden = NO;
                self.hotArray = [NSArray arrayWithArray:[[responseObject objectForKey:@"data"] objectForKey:@"list"]];
                [self HotBtn_WithArr:self.hotArray view:_view_hotSearch];
                [self relayOutUI];
                
            }
            
            
            
          [LoadingView dismiss];
        } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
            NSLog(@"response=%@/n error=%@",responseObject,error);
                   [self.textField resignFirstResponder];
                    if (!weakSelf.exceptionView && error) {
                        self.view_hotSearch.hidden = YES;
                        ExceptionCodeType type = ExceptionCodeTypeNoNetwork;
                        if (error.code == -1009) {
                            type = ExceptionCodeTypeNoNetwork;
                        }else if (error.code == -1001){
                            type = ExceptionCodeTypeRequestFailed;
                        }else if (error.code == 502 || error.code == 404){
                            type = ExceptionCodeTypeServerError;
                        }else{
                            type = ExceptionCodeTypeFailedToLoad;
                        }
                        weakSelf.exceptionView = [ExceptionView exceptionViewWithType:type];
                        ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:type handler:^(ExceptionViewAction *action) {
                            [self requestData];
                        }];
                        weakSelf.exceptionView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
                        [weakSelf.exceptionView addAction:retryAction];
                        [weakSelf.exceptionView showInView:self.view];
                    }
                [LoadingView dismiss];
        }];
        
//    }
    
    
}


#pragma mark --刷新UI
-(void)relayOutUI{
    
    [_view_hotSearch mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_containerView.mas_right).offset(0);
        make.top.equalTo(_containerView.mas_top).offset(0);
        make.height.mas_equalTo(@(_float_hotHeight));
        make.width.mas_equalTo(@(ScreenWidth));
    }];
    
    [_separateView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_containerView.mas_right);
        make.top.equalTo(_containerView.mas_top).offset(_float_hotHeight + 10);
        make.height.equalTo(@(10));
        make.left.equalTo(_containerView.mas_left);
    }];
    
    [_view_recentSearch mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_containerView.mas_right).offset(0);
        make.top.equalTo(_containerView.mas_top).offset(_float_hotHeight + 20);
        make.height.mas_equalTo(@(_float_recentHeight));
        make.width.mas_equalTo(@(ScreenWidth));
    }];
    [_containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_view_recentSearch.mas_bottom);
    }];
    if (self.recentSearchArr.count != 0) {
        _separateView.hidden = NO;
        _separateView.backgroundColor = RGB(242, 242, 242);
    }else{
        _separateView.hidden = YES;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
